package com.jason.practice.controller;

import com.alibaba.fastjson.JSONObject;
import com.jason.practice.response.Response;
import com.jason.practice.service.BaseCommonService;
import com.jason.practice.service.CitizenLoanInfoService;
import com.jason.practice.service.FinanceServiceInfoService;
import com.jason.practice.service.InsuranceProductInfoService;
import com.jason.practice.utils.FileZip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController("auth")
public class BaseCommonController {
    @Autowired
    private BaseCommonService baseCommonService;
    @Resource
    private FinanceServiceInfoService financeServiceInfoService;
    @Resource
    private CitizenLoanInfoService citizenLoanInfoService;
    @Resource
    private InsuranceProductInfoService insuranceProductInfoService;
    @GetMapping("/greeting")
    public Response getName(String name) {
        return baseCommonService.getUserByName(name);
    }
    @PostMapping("/batchExportExcel")
    public Response batchExportExcel(HttpServletResponse response, @RequestPart(value = "file") MultipartFile file, String localFolder) throws Exception {
        if (file == null) {
            Response.failed("文件不能为空！");
        }
        String fileName = file.getOriginalFilename();
        fileName = fileName.replaceAll(".zip","");
        long time = System.currentTimeMillis();
        String folder = localFolder + File.separator + time;
        File zipFile = FileZip.multipartFileToFile(file, folder);
        List<File> resultFiles = FileZip.zipUncompress(zipFile.getAbsolutePath(), folder);
        for (File f : resultFiles) {
            citizenLoanInfoService.uploadExcel(f);
            insuranceProductInfoService.uploadExcel(f);
            financeServiceInfoService.uploadExcel(f);
        }
        String lastFileName  = fileName + "_" + time +".zip";
        String resultPath = localFolder + File.separator + time + File.separator + lastFileName;
        File downloadFile = new File(resultPath);
        FileOutputStream fos2 = new FileOutputStream(downloadFile);
        FileZip.toZip(resultFiles, fos2);
        JSONObject result = new JSONObject();
        result.put("文件路径", resultPath);
        return Response.ok(result, "文件批量处理成功！");
    }

}
